
#define KEY_VAR

#include "key.h"
#include "cw3221e.h"
#include "exit_wakeup.h"


#define SHORT_TIME	2
#define LONG_TIME		100

uint8_t key_cur_status=0;
uint8_t key_old_status=0;
uint8_t read_key_status=0;
uint8_t	key_press_flag=0;

uint16_t key_press_cnt=0;

uint8_t pic_number=0;
uint8_t pic_update_flag=0;

void key_init(void)
{
	 __RCU_APB2_CLK_ENABLE(RCU_APB2_PERI_GPIOC);// Enable  GPIO clocks 
		
		gpio_mode_config(GPIOC,  GPIO_PIN_0 | GPIO_PIN_2,  GPIO_MODE_IN_PU);
}

void key_press_status(void)
{
	if(read_key1_status==0)
	{
		key_cur_status |=0x01;
	}
	else
	{
		key_cur_status &=0xfe;
	}
	if(read_key2_status==0)
	{
		key_cur_status |=0x02;
	}
	else
	{
		key_cur_status &=0xfd;
	}
}
void key_process(void)
{
	key_press_status();
	if(key_cur_status !=key_old_status)
	{
		key_old_status = key_cur_status;
		key_press_cnt=0;
		key_press_flag=0;
	}
	else
	{
		if(key_press_cnt<20000)
			key_press_cnt++;
		
		if(key_press_cnt>=SHORT_TIME)
		{
			if(key_cur_status==0x01)
			{
				if(key_press_flag==0)
				{
					key_press_flag=0x01;
					if(pic_number<3)pic_number++;
					else pic_number=0;
					pic_update_flag=1;
					printf("key1  %d !!!\r\n",pic_number);
				}
			}
			else if(key_cur_status ==0x02)
			{
				if(key_press_flag==0)
				{
					key_press_flag=0x02;
					if(pic_number)pic_number--;
					else pic_number=3;
					pic_update_flag=1;
					printf("key2  %d  !!!\r\n",pic_number);
				}
			}
			else if(key_cur_status ==0x03)
			{
				if(key_press_flag==0)
				{
					key_press_flag=0x04;
					printf("key1+2!!!\r\n");
				}
			}
			else
			{
				if(key_press_flag==0)
				{
					key_press_flag=0x04;
					printf("no key!!!\r\n");
				}
			}
		}
		
	}
}

uint8_t read_key_value(void)
{
	return pic_number;
}

void key_scan_task(void *pvParameters)
{
	uint8_t num=0;
	uint8_t iic_num=0;
	int8_t receive[30];
	int8_t sentdata[30];
	uint16_t	sleep_test_cnt=0;
	float percent=0;
	key_init();
	NTC_adc_init();
	i2c_configure();	
	uint8_t reset_cmd[] = {0xFE, 0x00};

//	exti_init();
    while(1)
    {	
			if(iic_num++>=30)
			{
				iic_num=0;
				I2C_WriteData(0x74,0, &sentdata[0],4);
				I2C_ReadData(0x74,21, &receive[21],1);
				if((receive[21]&0x80)||(sleep_test_cnt>10))
				{
					sleep_test_cnt=0;
					input_sleep_process();
				}
			}
				key_process();

			GetAdcValue();
			sentdata[0]=NTC1_temp;
			sentdata[1]=NTC2_temp;
			sentdata[2]=NTC4_temp;
			sentdata[3]=NTC3_temp;
			I2C_ReadData(0x74,22, &receive[22],5);
//			I2C_ReadData(0x74,0, &receive[22],4);
			
				vTaskDelay(10);
				if(num++>=100)
				{
					num=0;
					printf("key run process NTC1 :%+d  : %+d : %+d : %+d   ver: %.2x\r\n" ,NTC1_temp,NTC2_temp,NTC3_temp,NTC4_temp,receive[22]);
					printf("key run process NTC1 :%d  : %d : %d : %d\r\n" ,PA0_Adc_Value,PA1_Adc_Value,PA2_Adc_Value,PA3_Adc_Value);
					
					printf("CPW3221 INFO :%d  : %d : %d : %d : %d \r\n" ,receive[22],receive[23],receive[24],receive[25],receive[26]);
					sleep_test_cnt++;
				}
    }
}













